package ai.loa.ai;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

import ai.loa.controller.LOAController;
import ai.loa.controller.LOAGameObserver;
import ai.loa.utility.Parser;

/**
 * 
 * @author Administrator
 */

// Proxy per Il giocatore avversario
public class RemotePlayer extends Thread implements LOAGameObserver {

	private Socket socket;
	private Stato stato;
	private LOAController controller;

	public RemotePlayer(Socket sock, LOAController c) {
		super();
		socket = sock;
		controller = c;
	}

	@Override
	public void run() {

		try {

			BufferedReader br = new BufferedReader(new InputStreamReader(
					socket.getInputStream(), "ISO-8859-1"));
			while (true) {
				String message = br.readLine();
				controller.doMove(Parser.parse(message, stato.board));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void turnChanged(Stato stato) {
		this.stato = stato;
		if (stato.turno == 0 && stato.player == LOABoardConstants.PLAYER_1)
			return;

		String message = LOAAIPlayer.lastmove;

		try {
			PrintWriter pw = new PrintWriter(new OutputStreamWriter(
					socket.getOutputStream(), "ISO-8859-1"));
			pw.print(message);
			pw.flush();
		} catch (IOException ex) {
			ex.printStackTrace();
		}

	}
}
